package view;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;

import control.StudentDAO;
public class View extends JFrame implements ActionListener{
	private JTable table;
	private JButton btView,btExit;
	StudentDAO sd=new StudentDAO();
	public View(){
		add(createMainPanel());
		//set display
		setTitle("View");
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		pack();
		setLocationRelativeTo(null);
		setVisible(true);
	}
	public JPanel createMainPanel(){
		JPanel panel=new JPanel(new BorderLayout());
		panel.setBorder(new EmptyBorder(10, 10, 10, 10));
		panel.add(createTablePanel(),BorderLayout.CENTER);
		panel.add(createButtonPanel(),BorderLayout.PAGE_END);
		return panel;
	}
	public JPanel createTablePanel(){
		JPanel panel=new JPanel();
		panel.add(new JScrollPane(table=createTable()));
		return panel;
	}
	public JTable createTable(){
		JTable table=new JTable();
		return table;
	}
	public JPanel createButtonPanel(){
		JPanel panel=new JPanel();
		panel.add(btView=createButton("View"));
		panel.add(btExit=createButton("Exit"));
		return panel;
	}
	public JButton createButton(String text){
		JButton bt=new JButton(text);
		bt.addActionListener(this);
		return bt;
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		JButton bt=(JButton)e.getSource();
		if(bt.equals(btView)){
			btView_actionperformed();
		}else if(bt.equals(btExit)){
			btExit_actionperformed();
		}
	}
//	public void loadData(){
//		
//	}
	public void btView_actionperformed() {
		DefaultTableModel model=new DefaultTableModel();
		//StudentDAO sd=new StudentDAO();
		ResultSet rs=sd.getData();
		try {
			ResultSetMetaData rsMD=rs.getMetaData();
			int colNumber=rsMD.getColumnCount();
			String []arr=new String[colNumber];
			for(int i=0;i<colNumber;i++){
				arr[i]=rsMD.getColumnName(i+1);
			}
			model.setColumnIdentifiers(arr);
			while(rs.next()){
				for(int i=0;i<colNumber;i++){
					arr[i]=rs.getString(i+1);
				}
				model.addRow(arr);
			}
			table.setModel(model);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void btExit_actionperformed(){
		new MenuForm().setVisible(true);
		setVisible(false);
	}
}
